import React, { Component, MouseEvent } from "react";
import { List, Button } from "antd";

interface Props {
  todoItem: Object;
}

interface listItem {
  id: number;
  content: string;
}

interface State {
  listData: listItem[];
}

export default class TodoList extends Component<Props, State> {
  state = {
    listData: [],
  };

  componentDidMount() {
    if (Object.keys(this.props.todoItem).length > 0) {
      this.addTodoItem(this.props.todoItem);
    }
  }

  componentDidUpdate(prevProps: Props) {
    if (
      prevProps.todoItem !== this.props.todoItem &&
      Object.keys(this.props.todoItem).length > 0
    ) {
      this.addTodoItem(this.props.todoItem);
    }
  }

  addTodoItem(todoItem: Partial<listItem>) {
    this.setState((prevState) => ({
      listData: [
        ...prevState.listData,
        {
          id: prevState.listData.length, // 新添加项的 id 为当前 listData 的长度
          content: todoItem.content || "",
        },
      ],
    }));
  }
  handleClick = (index: number) => {
    console.log(index);
    this.setState((prevState: State) => ({
      listData: prevState.listData.filter((_, idx) => idx !== index),
    }));
  };
  render() {
    const listData: listItem[] = this.state.listData;
    return (
      <div>
        <List
          style={{ marginTop: "20px", height: "400px" }}
          bordered
          dataSource={listData}
          renderItem={(item, index) => (
            <List.Item>
              <List.Item.Meta description={item.content}></List.Item.Meta>
              <Button
                color="primary"
                variant="link"
                onClick={() => {
                  this.handleClick(index);
                }}
              >
                完成
              </Button>
            </List.Item>
          )}
        />
      </div>
    );
  }
}
